package com.zjm.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjm.json.util.JacksonUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;

/**
 * @author ZJM
 * @date 2024/4/18 21:47
 */
public class JacksonTest01 {

    @Test
    public void test() {
        // JSON字符串
        String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        // 创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 解析JSON字符串为Java对象
            Map map = objectMapper.readValue(json, Map.class);
            // 输出解析结果
            System.out.println(map.get("name"));
            System.out.println(map.get("age"));
            System.out.println(map.get("city"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test1() {
        // JSON字符串
        String json = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";

        try {
            // 将JSON字符串转换为Map
            Map<String, Object> map = JacksonUtils.jsonToMap(json);

            // 打印Map
            System.out.println("Map: " + map);

            // 修改Map中的值
            map.put("age", 35);

            // 将Map转换为JSON字符串
            String newJson = JacksonUtils.mapToJson(map);

            // 打印新的JSON字符串
            System.out.println("New JSON: " + newJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
